<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Project;
use App\Models\ProjectUser;
use App\Models\Role;
use App\Models\User;
use App\Models\UserAttendance;
use App\Models\UserEdu;
use App\Models\UserMore;
use App\Models\UserPayment;
use App\Models\UserWage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class UserService
{
    public function get($search,$formal){
        $sql = User::where('formal',$formal)->where('id','>',1)->with('roles')->with('more')->with('projects')->withCount('projects')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('name','like', '%'.$search.'%');
            });
        });
        return $sql;
    }

    public function getWage($issue_date){
        $sql = UserWage::with('user')->where('issue_date',$issue_date);
        return $sql;
    }

    public function userRoles($user_id,$project_id){
        $role_id = ProjectUser::where('user_id',$user_id)->where('project_id',$project_id)->pluck('role_id')->toArray();
        $data = Role::whereIn('id',$role_id)->get();
        return $data;
    }

    public function getAttendance($search){
        $sql = UserAttendance::with('user')->with('project');
        return $sql;
    }

    public function getPayment($search){
        $sql = UserPayment::with('user')->with('project');
        return $sql;
    }


    public function insert($input,$more){
        $res = [];
        foreach ($input as $k => $v) {
            $res[$k] = $v;
        }
        $is = User::where('mobile',$res['mobile'])->first();
        if($is){
            throw new InvalidRequestException('该手机号码已存在');
        }

        $is = User::where('idcard',$res['idcard'])->first();
        if($is){
            throw new InvalidRequestException('该身份证号码已存在');
        }

        try {
            $data = DB::transaction(function () use ($res,$more) {
                $res['password'] = Hash::make($res['password']);
                $user = User::create($res);
                $more['user_id'] = $user->id;
                $more = UserMore::create($more);
                return $user;
            });
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input,$more){
        unset($more['id']);
        try {
            $data = DB::transaction(function () use ($input,$more) {
                if(isset($input['password']) && $input['password']){
                    $input['password'] = Hash::make($input['password']);
                }
                $input['status'] = $input['status'] == true ? 1 : 0;
                $user = User::find($input['id']);
                foreach ($input as $k => $v) {
                    $user->$k = $v;
                }
                $user->save();
                $more = UserMore::where('user_id',$user->id)->update($more);
                return $user;
            });
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function insertEdu($input){
        unset($input['project_id']);
        try {
            $data = UserEdu::create($input);
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function updateEdu($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = UserEdu::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }


    public function insertWage($date){
        $is = UserWage::where('issue_date',$date)->first();
        if(!empty($is)){
            throw new InvalidRequestException('本月工资单已生成');
        }

        $user = User::where('id','>',1)->get();
        $res = [];
        foreach ($user as $k => $v) {
            $arr = [];
            $arr['user_id'] = $v->id;
            $arr['base'] = 0;
            $arr['issue_date'] = $date;
            $res[] = $arr;
        }
        try {
            $data = UserWage::insert($res);
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function updateWage($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = UserWage::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function status($data){
        try {
            $data->status =  $data->status ? 0 : 1;
            $data->save();
            if($data->id){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function userBindProject($input){
        throw new InvalidRequestException($input);
        $user = User::find($input['user_id']);
        $projects = json_decode($input['projects']);
        try {
            $user->projects()->sync($projects);
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function userBindProjectCert($input){
        try {
            $ProjectUser = ProjectUser::where('project_id',$input['project_id'])->where('user_id',$input['user_id'])->where('role_id',$input['role_id'])->first();
            $ProjectUser->cert_id = $input['cert_id'];
            $ProjectUser->save();
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function userBindProjectRole($input){

        $ProjectUser = ProjectUser::where('project_id',$input['project_id'])->where('user_id',$input['user_id'])->first();
        try {
            if($ProjectUser){
                $ProjectUser->roles = $input['roles'];
                $ProjectUser->cert_id = $input['cert_id'];
                $ProjectUser->save();
            }else{
                ProjectUser::insert($input);
            }

        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function bindProjectRole($input){
        $user = User::find($input['user_id']);
        try {
            if($input['id']){
                $user->projects()->updateExistingPivot($input['project_id'],[
                    'role_id' => $input['role_id'],
                    'start_date' => $input['start_date'],
                    'end_date' => $input['end_date'],
                    'work' => $input['work'],
                    'remarks' => $input['remarks'],
                ]);
                return true;
            }

            $arr = [
                'project_id' => $input['project_id'],
                'role_id' => $input['role_id'],
                'start_date' => $input['start_date'],
                'end_date' => $input['end_date'],
                'work' => $input['work'],
                'remarks' => $input['remarks'],
            ];
            $user->projects()->attach($input['project_id'],$arr);
            return true;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }


}